<script setup>
import {ref, onMounted} from "vue";
import {getCourses, getAllChapters, getAllSections} from '@/api/post.js';

// 本地数据存储
const courses = ref([]);
const chapters = ref([]);
const sections = ref([]);

// 树形结构数据
const treeData = ref([]);

// 获取课程、章节和小节数据
function fetchData() {
  Promise.all([getCourses(), getAllChapters(), getAllSections()])
    .then(([coursesRes, chaptersRes, sectionsRes]) => {
      courses.value = coursesRes.data.courses;
      chapters.value = chaptersRes.data.chapters;
      sections.value = sectionsRes.data.sections;
      // 数据获取完成后，构建树形结构
      buildTreeData();
    })
    .catch((e) => console.error("Failed to fetch data:", e));
}

// 构建树形结构数据
function buildTreeData() {
  treeData.value = courses.value.map((course) => {
    // 找到属于当前课程的章节
    const courseChapters = chapters.value.filter(
      (chapter) => chapter.courseId === course.courseId
    );

    // 构建章节节点
    const chapterNodes = courseChapters.map((chapter) => {
      // 找到属于当前章节的小节
      const chapterSections = sections.value.filter(
        (section) => section.chapterId === chapter.chapterId
      );

      // 构建小节节点
      const sectionNodes = chapterSections.map((section) => ({
        label: section.title,
        id: section.sectionId,
        nodeType: "section", // 使用 nodeType 区分节点类型
        ...section, // 保留小节的原始字段
      }));

      return {
        label: chapter.title,
        id: chapter.chapterId,
        nodeType: "chapter", // 使用 nodeType 区分节点类型
        children: sectionNodes,
        ...chapter, // 保留章节的原始字段
      };
    });

    return {
      label: course.title,
      id: course.courseId,
      nodeType: "course", // 使用 nodeType 区分节点类型
      children: chapterNodes,
      ...course, // 保留课程的原始字段
    };
  });
}

// 打印树形数据
console.log(treeData.value);

// 组件加载成功后调用 fetchData
onMounted(() => {
  fetchData();
});

// 点击节点时的回调
const emit = defineEmits(['select-section']); // 定义事件
const handleNodeClick = (data) => {
  if (data.nodeType === 'section') { // 检查 nodeType
    console.log("Section clicked, content type:", data.type); // 打印内容类型
    emit('select-section', data); // 触发事件，传递当前选中的小节数据
  }
};

// 树形组件的配置
const defaultProps = {
  children: "children",
  label: "label",
};
</script>

<template>
  <div class="directory">
    <el-tree
      :data="treeData"
      :props="defaultProps"
      @node-click="handleNodeClick"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <!-- 自定义节点内容 -->
      <template #default="{ node }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<style scoped>
.directory {
  width: 300px;
  overflow-y: auto;
  border-right: 1px solid #ddd;
  padding: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4px;
}
</style>
